/**
 * createUser:曾维录
 * FileName: GlobalExceptionHandler
 * Author:   14562
 * Date:     2019/9/17 13:48
 * Description: 全局异常处理类
 */
package com.javatom.notes.common.exception;



import com.javatom.notes.common.enums.HttpReponseCodeEnum;
import com.javatom.notes.common.model.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 参数非法异常
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R illegalArgumentException(IllegalArgumentException e) {
        return R.fail(HttpReponseCodeEnum.PARAM_ERR);
    }

    /**
     * 参数错误
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return R.fail(HttpReponseCodeEnum.PARAM_ERR);
    }

    /**
     * 资源不存在
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R noHandlerFoundException(NoHandlerFoundException e) {
        return R.fail(HttpReponseCodeEnum.NOT_FOUND);
    }
    /**
     * 请求方法不支持
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R noHandlerFoundException(HttpRequestMethodNotSupportedException e) {
        return R.fail(HttpReponseCodeEnum.ERR_405);
    }

    /**
     * 运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R noHandlerFoundException(BaseException e) {
        return R.fail(e.getCode(),e.getMsg());
    }
    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R noHandlerFoundException(Exception e) {
        e.printStackTrace();
        return R.fail(HttpReponseCodeEnum.INTERNAL_SERVER_ERROR);
    }

}
